import ForceUtil from '@/ForceUtil';
import GroupUtil from '@/GroupUtil';
import SelectUtil from '@/SelectUtil';

export default class SelectCommon {
    static getAllyUnitInRange(中心: unit, 半径: number, x = GetUnitX(中心), y = GetUnitY(中心)) {
        let group = GroupUtil.groupObjectPool.borrowObject();
        GroupEnumUnitsInRange(group, x, y, 半径, null);
        let units: unit[] = [];
        let myPlayer = GetOwningPlayer(中心);
        for (let i = 0; i <= 1000000; i++) {
            let unitHandle = FirstOfGroup(group);
            if (!IsHandle(unitHandle)) {
                break;
            }
            GroupRemoveUnit(group, unitHandle);
            if (GetUnitState(unitHandle, UNIT_STATE_LIFE) < 1) {
                continue;
            }
            if (IsUnitAlly(unitHandle, myPlayer)) {
                units.push(unitHandle);
            }
        }
        GroupUtil.groupObjectPool.returnObject(group);
        return units;
    }

    static getAllyUnitInRangeExcludeCenterUnit(中心: unit, 半径: number) {
        let all = SelectCommon.getAllyUnitInRange(中心, 半径, GetUnitX(中心), GetUnitY(中心));
        for (let item of all) {
            if (item == 中心) {
                all.splice(all.indexOf(item), 1);
                break;
            }
        }
        return all;
    }
    static getDeathUnitsInRange(x: number, y: number, r: number) {
        let group = GroupUtil.groupObjectPool.borrowObject();
        GroupEnumUnitsInRange(group, x, y, r, null);
        let units: unit[] = [];
        for (let i = 0; i <= 1000000; i++) {
            let unitHandle = FirstOfGroup(group);
            if (!IsHandle(unitHandle)) {
                break;
            }
            GroupRemoveUnit(group, unitHandle);
            if (GetUnitState(unitHandle, UNIT_STATE_LIFE) > 1) {
                continue;
            }
            units.push(unitHandle);
        }
        GroupUtil.groupObjectPool.returnObject(group);
        return units;
    }
    static getAllPlayerAliveUnits() {
        let count = ForceUtil.getUserCount();
        let all: unit[] = [];
        for (let i = 0; i < count; i++) {
            let arr = SelectUtil.getPlayerUnits(i);
            for (let u of arr) {
                if (!IsHandle(u)) continue;
                if (IsUnitAliveBJ(u)) {
                    all.push(u);
                }
            }
        }
        return all;
    }
    static getAllPlayerAvilableUnits() {
        let count = ForceUtil.getUserCount();
        let all: unit[] = [];
        for (let i = 0; i < count; i++) {
            let arr = SelectUtil.getPlayerUnits(i);
            for (let u of arr) {
                if (!IsHandle(u)) continue;
                if (GetUnitAbilityLevel(u, 'Aloc') == 1) continue;
                if (IsUnitAliveBJ(u)) {
                    all.push(u);
                }
            }
        }
        return all;
    }
}
